package com.digitalchina.lxnsy.base;

import android.app.Activity;
import android.os.Handler;
import android.text.TextUtils;


import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.lzy.okhttputils.model.HttpParams;

import java.io.File;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class BaseApi {
    /**
     * 图片压缩 并上传
     *
     * @param activity
     * @param isCompress 是否压缩
     * @param filePath   文件路径
     * @param handler
     */
    public static void upload(final Activity activity, boolean isCompress, final String filePath, final Handler handler) {

        if (isCompress)
            Luban.with(activity)
                    .load(new File(filePath))
                    .ignoreBy(100)
                    .filter(new CompressionPredicate() {
                        @Override
                        public boolean apply(String path) {
                            return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                        }
                    })
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        }

                        @Override
                        public void onSuccess(File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件
                            HttpParams params = new HttpParams();
                            params.put("file", file);
                            params.put("appId", "app018");

                            OkHttpUtil.post(activity, URL.URL_FILE_UPLOAD, "", params, handler, MSG.upload, MSG.upload_failed);
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                        }
                    }).launch();
        else {
            //不压缩 直接上传
            HttpParams params = new HttpParams();
            params.put("file", new File(filePath));
            params.put("appId", "app018");
            OkHttpUtil.post(activity, URL.URL_FILE_UPLOAD, "", params, handler, MSG.upload, MSG.upload_failed);
        }

    }
}
